package com.oedtech.esl.controller.eslController;

import com.oedtech.esl.controller.BaseController;
import com.oedtech.esl.json.JsonResult;
import com.oedtech.esl.model.esl.EslTab;
import com.oedtech.esl.repository.esl.EslTabDao;
import com.oedtech.esl.service.eslService.EslTabService;
import com.oedtech.esl.service.nettyService.DataService;
import com.oedtech.esl.socket.BsChannelMap;
import io.netty.channel.Channel;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.*;
import java.io.IOException;
import java.security.Principal;
import java.util.*;

@RestController
@RequestMapping("/esl_rest")
public class EslRestController extends BaseController {

    @Autowired
    private DataService dataService;
    @Autowired
    private EslTabDao eslTabDao;
    @Autowired
    private EslTabService eslTabService;
    /**
     * esl页面初始化数据
     * @return map,map中包含skuList=所有sku数据，networkIPs=所有已连接的基站ip
     */
    @RequestMapping(value="/find_all")
    public Map<String,Object> findAll(){
        return getStringObjectMap();
    }

    public Map<String, Object> getStringObjectMap() {
        Map<String,Object>map=new HashMap<>();
        getNetworkIPs( map);

        return map;
    }



    @RequestMapping(value="/find_networkIPList")
    public Map<String,Object> findNetworkIPList(){
        Map<String,Object>map=new HashMap<>();
        getNetworkIPs(map);
        return map;
    }

    private void getNetworkIPs( Map<String, Object> map) {
        Set<String> bsNetworkIP= BsChannelMap.getInstance().keySet();

            map.put("networkIPs",bsNetworkIP);//已连接的基站
    }



    //删除标签
    @RequestMapping("/delete_esl")
    public void delectEsl(@RequestParam(value="eslIds")String[]eslIds) {
        if(eslIds==null||eslIds.length<=0)return;
        eslTabService.deleteEsl(eslIds);
    }


    /**
     * 发送p8指令给基站
     * @param networkIP  基站ip
     * @return    返回操作结果
     */
    @RequestMapping("/send_p8")
    public JsonResult p8Send(@RequestParam(value="networkIP")String networkIP){
        logger.info(networkIP+":sendP8");
        Channel channel= BsChannelMap.getInstance().get(networkIP);
            dataService.p8Send(channel);
            return new JsonResult("msg",null,"success");
    }

    /**
     * 发送p9指令给基站
     * @param networkIP   基站ip
     * @return   执行结果
     */
    @RequestMapping("/send_p9")
    public JsonResult p9Send(@RequestParam(value="networkIP")String networkIP){
        logger.info(networkIP+":sendP9");
        Channel channel= BsChannelMap.getInstance().get(networkIP);
            dataService.p9Send(channel);
        return new JsonResult("msg",null,"success");
    }







    /**
     * 标签列表分页查询
     * @param page 页码
     * @param size 显示条数
     * @param sortStr   排序字段
     * @param sortAscOrDesc  正序或倒序
     * @param searchObj  查询条件
     * @return   包含esl类的Page类
     */
    @RequestMapping("/eslTab/listByPage")
    @ResponseBody
    public Page<EslTab> listByPage(int page, int size, String sortStr, boolean sortAscOrDesc, String searchObj, Principal principal)
    {

        Specification<EslTab> specification = getSpecification(searchObj,principal.getName());

        if (StringUtils.isEmpty(sortStr))
        {
            return eslTabDao.findAll(specification, PageRequest.of(page, size));

        }
        else
        {
            return eslTabDao.findAll(specification, PageRequest.of(page, size, new Sort((sortAscOrDesc ? Sort.Direction.ASC : Sort.Direction.DESC), sortStr,"networkIP")));
        }
    }
    private Specification getSpecification(String searchObj,String username)
    {
        JSONObject search = (JSONObject) JSONValue.parse(searchObj);

        Specification<EslTab> specification = new Specification<EslTab>()
        {
            @Override
            public Predicate toPredicate(Root<EslTab> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder)
            {
                List<Predicate> queryList = new ArrayList<Predicate>();
//                queryList.add(criteriaBuilder.equal(root.get("username"),username));//只查询当前用户的信息
                if (search.get("tinyIP") != null && !StringUtils.isEmpty(search.get("tinyIP") + ""))
                {
                    queryList.add(criteriaBuilder.like(root.get("tinyIP"), "%"+search.get("tinyIP") + "%"));
                }
                if (search.get("storeCode") != null && !StringUtils.isEmpty(search.get("storeCode") + ""))
                {
                    queryList.add(criteriaBuilder.like(root.get("storeCode"), "%"+search.get("storeCode") + "%"));
                }
                if (search.get("networkIP") != null && !StringUtils.isEmpty(search.get("networkIP") + ""))
                {
                    queryList.add(criteriaBuilder.like(root.get("networkIP"), "%"+search.get("networkIP")+"%"));
                }
                if (search.get("gidIndex") != null && !StringUtils.isEmpty(search.get("gidIndex") + ""))
                {
                    queryList.add(criteriaBuilder.equal(root.get("gidIndex"), search.get("gidIndex")));
                }
                if (search.get("versionStr") != null && !StringUtils.isEmpty(search.get("versionStr") + ""))
                {
                    queryList.add(criteriaBuilder.like(root.get("versionStr"), "%"+search.get("versionStr")+"%"));
                }


                if (queryList.size() > 0)
                {
                    criteriaQuery.where(criteriaBuilder.and(queryList.toArray(new Predicate[queryList.size()])));
                }
                return criteriaQuery.getRestriction();
            }
        };

        return specification;
    }



    @RequestMapping("/refresh")
    public void reflashImg(@RequestParam("eslIds")String[]eslIds) {
        eslTabService.refresh(eslIds);
    }

    @RequestMapping("/demo_img")
    public void reflashDemoImg(@RequestParam("eslIds")String[]eslIds,@RequestParam("inch")Integer inch){
        try {
            eslTabService.refreshDemoImg(eslIds,inch);
        } catch (IOException e) {
            logger.warn(e.getMessage());
        }
    }

}
